<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" type="text/css" href="./lib/bootstrap.css">
</head>
<body>
  <form>
    <input type="file" name="myfile" id="myfile">
    <input type="button" value="提交" id="btn">
  </form>
  <div>
    <img src="" id="test">
  </div>
  <div class="progress" style="width: 500px; margin: 15px 10px;">
    <div class="progress-bar progress-bar-striped active" style="width: 0%" id="percent">
      0%
    </div>
  </div>
  <script type="text/javascript">
    var btn = document.getElementById('btn')
    btn.onclick = function () {
      var file = document.getElementById('myfile').files[0]
      if (!file) {
        alert('请选择文件')
        return
      }
      var fd = new FormData()
      fd.append('avatar', file)

      // 把得到的文件内容进行上传
      var xhr = new XMLHttpRequest()
      // 监听文件上传的进度
      xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
          // 计算上传进度
          var num = Math.ceil((e.loaded / e.total) * 100)
          console.log(num)
          // 把num进度值更新到样式标签中
          var p = document.getElementById('percent')
          // 更新进度条效果
          p.style = 'width: ' + num + '%'
          p.innerHTML = num + '%'
        }
      }
      xhr.upload.onload = function (e) {
        var p = document.getElementById('percent')
        // 删除标签已有的类名
        p.classList.remove('progress-bar-striped', 'active')
        p.classList.add('progress-bar-success')
      }

      xhr.open('post', 'http://www.liulongbin.top:3006/api/upload/avatar')
      // 处理文件上传
      
      xhr.send(fd)
      
      xhr.onload = function () {
        if (xhr.status === 200) {
          console.log(xhr.responseText)
        }
      }

      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          var ret = xhr.responseText
          ret = JSON.parse(ret)
          var img = document.getElementById('test')
          img.setAttribute('src', 'http://www.liulongbin.top:3006' + ret.url)
        }
      }
    }
  </script>
</body>
</html>